# -*- coding:utf-8 -*-
from tornado import gen
import os

from appcommon.framework import WebBaseHandler
from common import utiltool
from common import timetool
import models as adm
import settings
import base64


class SaveAdTypeHandler(WebBaseHandler):
    """
    修改广告归属
    """
    @gen.coroutine
    def post(self):
        ad_id = self.get_argument('ad_id', '')
        ad_type = self.get_arguments('ad_type')
        yield adm.save_ad_type(ad_id, ad_type)
        utiltool.response_write(self, {"code": "0"})


class UploadAdImgHandler(WebBaseHandler):
    """
    上传图片
    """
    @gen.coroutine
    def post(self):
        file_metas = self.request.files['file']  # 提取表单中‘name’为‘file’的文件元数据
        current_time = timetool.get_timestamp()
        data = []
        for meta in file_metas:
            upload_path = settings.IMG_BASE_PATH + 'system/'
            os.path.exists('upload_path')
            filename = 'ad_' + str(current_time) + '.' +meta['filename'].split('.')[-1]
            filepath = os.path.join(upload_path, filename)
            with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
            data.append(settings.IMG_BASE_URL + 'system/{}'.format(filename))
        res = {"code": "0", "url": data[0] if data else ''}
        utiltool.response_write(self, res)



class AddAdHandler(WebBaseHandler):
    """
    上广告
    """
    @gen.coroutine
    def post(self):
        print self.request.arguments
        title_url = self.get_argument('title_url', '')
        content = self.get_argument('content', '')
        title = self.get_argument('title', '')
        type = self.get_argument('type', '0')
        url = self.get_argument('url', '')
        current_time = timetool.get_timestamp()
        res = yield adm.add_ad_2_mysql(title_url, title, content, current_time, type, url)
        result = {"code": "0", "msg": u"插入成功"} if res else {"code": "1", "msg": u"插入失败"}
        utiltool.response_write(self, result)



class AdDetailHandler(WebBaseHandler):
    """
    广告详情
    """
    @gen.coroutine
    def get(self):
        ad_id = self.get_argument('ad_id', '')
        info = yield adm.get_ad_detail(ad_id)
        # info['pubtime'] = timetool.convert_timestamp_to_date(info['pubtime'])
        print info
        utiltool.response_write(self, {"code": "0", "info": info})



class UpdateAdHandler(WebBaseHandler):
    """
    改广告
    """
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        title_url = self.get_argument('title_url', '')
        content = self.get_argument('content', '')
        title = self.get_argument('title', '')
        ad_id = self.get_argument('ad_id', '0')
        type = self.get_argument('type', '0')
        url = self.get_argument('url', '')
        res = yield adm.update_ad_2_mysql(title_url, title, content, ad_id, current_time, type, url)
        result = {"code": "0", "msg": u"修改成功"} if res else {"code": "1", "msg": u"修改失败"}
        utiltool.response_write(self, result)


class AdListHandler(WebBaseHandler):
    """
    广告列表
    """
    @gen.coroutine
    def get(self):
        info = yield adm.get_ad_list()
        for item in info:
            item['pubtime'] = timetool.convert_timestamp_to_date(item['pubtime'])
        res = dict(
            code="0",
            info=info
        )
        utiltool.response_write(self, res)


class DelAdHandler(WebBaseHandler):
    """
    删广告
    """
    @gen.coroutine
    def post(self):
        ad_id = self.get_argument('ad_id', '0')
        res = yield adm.del_ad_2_mysql(ad_id)
        result = {"code": "0", "msg": u"删除成功"}
        utiltool.response_write(self, result)


class UpdateSharePicHandler(WebBaseHandler):
    """
    修改分享图片
    """
    @gen.coroutine
    def post(self):
        pic_type = self.get_argument('pic_type', '1')  # 1：share_pic  2:couch_share_pic
        base64str = self.get_argument('base64str', '')
        if base64str:
            current_time = timetool.get_timestamp()
            file_type = base64str.split(';')[0].split('/')[-1]
            pic = base64str.split(';')[1].split(',')[-1]
            upload_path = settings.IMG_BASE_PATH + 'system/'
            os.path.exists('upload_path')
            if pic_type == '1':
                filename = 'share_pic' + str(current_time) + '.' + file_type
            elif pic_type == '2':
                filename = 'couch_share_pic' + str(current_time) + '.' + file_type
            elif pic_type == '3':
                filename = 'bottom_pic' + str(current_time) + '.' + file_type
            else:
                filename = 'couch_bottom_pic' + str(current_time) + '.' + file_type
            filepath = os.path.join(upload_path, filename)
            img_data = base64.b64decode(pic)
            with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(img_data)
            yield adm.update_share_pic(filename, pic_type)
        result = {"code": "0", "msg": u"上传成功"}
        utiltool.response_write(self, result)


class GetSharePicHandler(WebBaseHandler):
    """
    获取分享图片
    """
    @gen.coroutine
    def post(self):
        info = yield adm.get_share_pic()
        info['share_pic'] = settings.IMG_BASE_URL + "system/{}".format(info['share_pic'])
        info['couch_share_pic'] = settings.IMG_BASE_URL + "system/{}".format(info['couch_share_pic'])
        info['bottom_pic'] = settings.IMG_BASE_URL + "system/{}".format(info['bottom_pic'])
        info['couch_bottom_pic'] = settings.IMG_BASE_URL + "system/{}".format(info['couch_bottom_pic'])
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)
